<template>
  <div class="volunteer-management-container">
    <el-card class="filter-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>志愿者管理</h3>
          <el-button type="primary" @click="handleCreateVolunteer">
            <el-icon><plus /></el-icon> 新增志愿者
          </el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- <el-form-item label="用户ID">
          <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable />
        </el-form-item> -->
        <el-form-item label="姓名">
          <el-input v-model="searchForm.realName" placeholder="请输入姓名" clearable />
        </el-form-item>
        
        <el-form-item label="学校">
          <el-input v-model="searchForm.school" placeholder="请输入学校" clearable />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card" shadow="hover">
      <el-table
        :data="volunteerList"
        border
        stripe
        highlight-current-row
        :row-key="row => row.id"
        @row-dblclick="handleEditVolunteer"
      >
        <el-table-column prop="id" label="档案ID" width="80" align="center" />
        <el-table-column prop="userId" label="用户ID" width="100" align="center" />
        <el-table-column prop="realName" label="姓名" min-width="100" />
        <el-table-column label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ getGenderName(row.gender) }}
          </template>
        </el-table-column>
        <el-table-column prop="school" label="学校" min-width="120" />
        <el-table-column prop="major" label="专业" min-width="120" />
        <el-table-column prop="volunteerHours" label="服务时长" width="100" align="right" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditVolunteer(row)">
              <el-icon><edit /></el-icon> 编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteVolunteer(row)">
              <el-icon><delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑志愿者对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑志愿者' : '新增志愿者'"
      width="40%"
    >
      <el-form 
        :model="formData" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="formData.userId" placeholder="请输入用户ID" />
        </el-form-item>
        
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        
        <el-form-item label="学校" prop="school">
          <el-input v-model="formData.school" placeholder="请输入学校" />
        </el-form-item>
        
        <el-form-item label="专业" prop="major">
          <el-input v-model="formData.major" placeholder="请输入专业" />
        </el-form-item>
        
        <el-form-item label="服务时长" prop="volunteerHours">
          <el-input-number 
            v-model="formData.volunteerHours" 
            :min="0" 
            :max="10000" 
            :step="0.1" 
            placeholder="请输入服务时长"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select 
            v-model="formData.status" 
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveVolunteer">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <p>确定要删除志愿者 <span class="user-name">{{ deleteUserName }}</span> 吗？</p>
      <p class="warning-text">此操作不可撤销！</p>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete
} from '@element-plus/icons-vue';
import request from '@/utils/request';

// 搜索表单
const searchForm = reactive({
  //userId: '', // 添加用户ID搜索字段
  realName: '',
  school: '',
  status: ''
});

// 表格数据
const volunteerList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 对话框状态
const dialogVisible = ref(false);
const isEditMode = ref(false);
const formData = reactive({
  id: null,
  userId: null,
  realName: '',
  gender: 1,
  idCard: '',
  school: '',
  major: '',
  volunteerHours: 0,
  status: 1
});

// 表单验证规则
const rules = reactive({
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    //{ type: 'number', message: '请输入有效的用户ID', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  school: [
    { required: true, message: '请输入学校', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  volunteerHours: [
    { required: true, message: '请输入服务时长', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
    //{ min: 0, message: '服务时长不能为负数', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
});

// 删除对话框
const deleteDialogVisible = ref(false);
const deleteUserId = ref(null);
const deleteUserName = ref('');

// 表单引用
const formRef = ref(null);

// 生命周期钩子
onMounted(() => {
  fetchVolunteerList();
});

// 获取志愿者列表
const fetchVolunteerList = async () => {
  loading.value = true;
  
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      userId: searchForm.userId || undefined, // 添加用户ID参数
      realName: searchForm.realName || undefined,
      school: searchForm.school || undefined,
      status: searchForm.status || undefined
    };
    
    const response = await request.get('/user-service/user/profile/list', { params });
    
    if (response.code === 200) {
      volunteerList.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取志愿者列表失败');
    }
  } catch (error) {
    ElMessage.error('获取志愿者列表失败，请重试');
    console.error('获取志愿者列表错误:', error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchVolunteerList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.userId = ''; // 重置用户ID搜索字段
  searchForm.realName = '';
  searchForm.school = '';
  searchForm.status = '';
  currentPage.value = 1;
  fetchVolunteerList();
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchVolunteerList();
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchVolunteerList();
};

// 打开新增志愿者对话框
const handleCreateVolunteer = () => {
  isEditMode.value = false;
  // 重置表单数据
  Object.assign(formData, {
    id: null,
    userId: null,
    realName: '',
    gender: 1,
    idCard: '',
    school: '',
    major: '',
    volunteerHours: 0,
    status: 1
  });
  dialogVisible.value = true;
  
  // 重置表单验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
};

// 打开编辑志愿者对话框
const handleEditVolunteer = (row) => {
  isEditMode.value = true;
  // 复制数据到表单
  Object.assign(formData, {
    id: row.id,
    userId: row.userId,
    realName: row.realName,
    gender: row.gender,
    idCard: row.idCard,
    school: row.school,
    major: row.major,
    volunteerHours: row.volunteerHours,
    status: row.status
  });
  dialogVisible.value = true;
};

// 保存志愿者
const saveVolunteer = async () => {
  // 触发表单验证
  if (!formRef.value) return;
  
  const valid = await formRef.value.validate();
  if (!valid) return;
  
  try {
    let response;
    let successMessage;
    
    if (isEditMode.value) {
      // 编辑志愿者
      response = await request.post('/user-service/user/profile/update', formData);
      successMessage = '志愿者信息更新成功';
    } else {
      // 新增志愿者
      response = await request.post('/user-service/user/profile/add', formData);
      successMessage = '志愿者创建成功';
    }
    
    if (response.code === 200) {
      ElMessage.success(successMessage);
      dialogVisible.value = false;
      fetchVolunteerList();
    } else {
      ElMessage.error(response.message || (isEditMode.value ? '志愿者信息更新失败' : '志愿者创建失败'));
    }
  } catch (error) {
    ElMessage.error(isEditMode.value ? '志愿者信息更新失败，请重试' : '志愿者创建失败，请重试');
    console.error(isEditMode.value ? '更新志愿者错误' : '创建志愿者错误', error);
  }
};

// 处理删除志愿者
const handleDeleteVolunteer = (row) => {
  deleteUserId.value = row.id;
  deleteUserName.value = row.realName;
  deleteDialogVisible.value = true;
};

// 确认删除志愿者
const confirmDelete = async () => {
  try {
    // 修改为使用params传递id，与后端@RequestParam匹配
    const response = await request.post(`/user-service/user/profile/delete?id=${deleteUserId.value}`);
    
    if (response.code === 200) {
      ElMessage.success('志愿者删除成功');
      deleteDialogVisible.value = false;
      // 如果删除的是当前页最后一条数据，且不是第一页，则返回上一页
      if (volunteerList.value.length === 1 && currentPage.value > 1) {
        currentPage.value -= 1;
      }
      fetchVolunteerList();
    } else {
      ElMessage.error(response.message || '志愿者删除失败');
    }
  } catch (error) {
    ElMessage.error('志愿者删除失败，请重试');
    console.error('删除志愿者错误:', error);
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString();
};

// 获取性别名称
const getGenderName = (gender) => {
  const genders = {
    1: '男',
    2: '女'
  };
  return genders[gender] || '未知';
};

// 获取状态名称
const getStatusName = (status) => {
  const statuses = {
    1: '正常',
    0: '禁用'
  };
  return statuses[status] || '未知';
};

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    1: 'success',
    0: 'danger'
  };
  return types[status] || 'info';
};
</script>

<style scoped lang="scss">
.volunteer-management-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-top: 10px;
}

.table-card {
  min-height: 500px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.warning-text {
  color: #ff4d4f;
  margin-top: 10px;
}

.user-name {
  font-weight: bold;
  color: #2563eb;
}

/* 对话框样式调整 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}
</style>    